package com.xm.xmapp.http;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.xm.xmapp.base.ReqBaseBean;
import com.xm.xmapp.base.RespBaseBean;
import com.xm.xmapp.tool.BeanTool;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by LDW on 2017/7/14.
 */
public class PostData extends Request<String> {

    private NetWorkData mListener;
    private int code;
    private ReqBaseBean mReqBaseBean;
    public PostData(ReqBaseBean mReqBaseBean,int code, NetWorkData mListener){
        this(Request.Method.POST ,mReqBaseBean.getUrl() ,new NetWorkError(mListener,code));
        this.mListener = mListener;
        this.mReqBaseBean = mReqBaseBean;
        this.code = code;
    }
    public PostData(int method, String url, Response.ErrorListener listener) {
        super(method, url, listener);
    }

    public byte[] getBody() throws AuthFailureError {


        byte[] byteSize = null;
        try {
            byteSize = BeanTool.getStr(mReqBaseBean);
        } catch (Exception e){

        }
        return byteSize;

    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) {

        String str = null;
        try {
            str = new String(networkResponse.data, "utf-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return Response.success(str, HttpHeaderParser.parseCacheHeaders(networkResponse));
    }

    @Override
    protected void deliverResponse(String s) {
//        mListener.dissMissDialog(code);
        RespBaseBean respBaseBean = JSON.parseObject(s,RespBaseBean.class);
        switch (respBaseBean.errCode) {
            case 0:
                mListener.onResponse(code,respBaseBean.data);
                break;
            default:
                mListener.onErrorResponse(code,s);
                break;
        }

    }
}
